package com.cuz.hot100;

import com.cuz.hot100.datastruck.ListNode;

public class Q21MergeTwoSortedLinkedLists {
    public static ListNode mergeTwoLists1(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        if (list1.val < list2.val) {
            list1.next = mergeTwoLists1(list1.next, list2);
            return list1;
        } else {
            list2.next = mergeTwoLists1(list1, list2.next);
            return list2;
        }

    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(3);
        ListNode node3 = new ListNode(6);
        node1.next = node2;
        node2.next = node3;
        ListNode head1 = new ListNode(2);
        ListNode head2 = new ListNode(4);
        ListNode head3 = new ListNode(5);
        ListNode head4 = new ListNode(6);
        ListNode head5 = new ListNode(7);
        head1.next = head2;
        head2.next = head3;
        head3.next = head4;
        head4.next = head5;
        ListNode listNode = mergeTwoLists2(node1, head1);
        while (listNode!=null){
            System.out.println(listNode.val);
            listNode=listNode.next;
        }
    }

    public static ListNode mergeTwoLists2(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        ListNode preHead = new ListNode();
        if (list1.val < list2.val) {
            preHead.next = list1;
            list1 = list1.next;
        } else {
            preHead.next = list2;
            list2 = list2.next;
        }
        ListNode cur = preHead.next;
        while (list1 != null && list2 != null) {
            if (list1.val <= list2.val) {
                ListNode temp = list1.next;
                cur.next = list1;
                list1.next = null;
                list1 = temp;
            } else {
                ListNode temp = list2.next;
                cur.next = list2;
                list2.next = null;
                list2 = temp;
            }
            cur = cur.next;
        }
        if (list1 == null) {
            cur.next = list2;
        } else {
            cur.next = list1;
        }
        return preHead.next;
    }
}
